

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/IKKIS_LOGO.png">
  <link rel="icon" href="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/IKKIS_LOGO.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Ikki">
  <meta name="keywords" content="">
  
    <meta name="description" content="WebSockets_API是HTML5开始提供的一种浏览器与服务器进行全双工通讯的网络技术">
<meta property="og:type" content="article">
<meta property="og:title" content="websocket">
<meta property="og:url" content="http://81.68.132.127/2022/09/27/network/websocket/index.html">
<meta property="og:site_name" content="IKKI">
<meta property="og:description" content="WebSockets_API是HTML5开始提供的一种浏览器与服务器进行全双工通讯的网络技术">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/beijing/iTab-28rjj6.png">
<meta property="article:published_time" content="2022-09-27T07:51:34.000Z">
<meta property="article:modified_time" content="2022-10-07T11:59:39.607Z">
<meta property="article:author" content="Ikki">
<meta property="article:tag" content="网络知识">
<meta property="article:tag" content="websocket">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/beijing/iTab-28rjj6.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>websocket - IKKI</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  



  
<link rel="stylesheet" href="/fluid/css/fluid-extention.css">
<link rel="stylesheet" href="/fluid/css/nihao.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"81.68.132.127","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":3},"lazyload":{"enable":true,"loading_img":"https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 100vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Ikki-BUG制造者</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('http://image.ikki0603.cn') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="websocket"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-09-27 15:51" pubdate>
          2022年9月27日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          9.4k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          78 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
        <div class="scroll-down-bar">
          <i class="iconfont icon-arrowdown"></i>
        </div>
      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">websocket</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2022年10月7日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="1-websocket介绍"><a href="#1-websocket介绍" class="headerlink" title="1.websocket介绍"></a>1.websocket介绍</h1><ul>
<li>WebSockets_API是HTML5开始提供的一种浏览器与服务器进行全双工通讯的网络技术</li>
<li>通俗地讲：在客户端和服务器保有一个持久的连接，两边可以在任意时间开始发送数据</li>
<li>HTML5开始提供的一种浏览器与服务器进行全双工通讯的网络技术</li>
<li>属于应用层协议，它基于TCP传输协议，并复用HTTP的握手通道</li>
<li>虽然 http1.1 默认开启了 keep-alive 长连接保持了这个 TCP 通道使得在一个 HTTP 连接中可以发送多个请求，接受多个响应，但是一个请求只能有一个响应，而且这个响应也是被动的，不能主动发起</li>
<li>WebSocket 虽然是独立于 HTTP 的一种协议，但是 WebSocket 必须依赖 HTTP 协议进行一次握手（在握手阶段是一样的），我手成功后，数据就直接从 TCP 通道传输，与 HTTP 无关了，可以用一张图理解两者有交集，但并不是全部。<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-20-58-48.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload></li>
</ul>
<h2 id="socket"><a href="#socket" class="headerlink" title="socket"></a>socket</h2><ul>
<li>socket 也被称为套接字，与 HTTP 和 WebSocket 不一样，socket 不是协议，它是在程序层面上对传输层协议（可以主要理解为 TCP / IP）的接口封装。可以理解为一个能够提供端对端的通信的调用接口（API）。</li>
<li>对于程序员而言，其需要在 A 端创建一个 socket 实例，并为这个实例提供其所要连接的 B 端的 IP 地址和端口号，而在 B 端创建另一个 socket 实例，并且绑定本地端口号来进行监听。当 A 和 B 建立连接后，双方就建立了一个端对端的 TCP</li>
</ul>
<h2 id="websocket和HTTP有什么不一样小结"><a href="#websocket和HTTP有什么不一样小结" class="headerlink" title="websocket和HTTP有什么不一样小结"></a>websocket和HTTP有什么不一样小结</h2><ul>
<li>双向通信</li>
<li>数据格式比较轻量，性能开销小，通信高效</li>
<li>协议控制的数据包头部较小，而HTTP协议每次通信都需要携带完整的头部</li>
<li>更好的二进制支持</li>
<li>没有同源限制，客户端可以与任意服务器通信</li>
<li>与 HTTP 协议有着良好的兼容性。默认端口也是80和443，并且握手阶段采用 HTTP 协议，因此握手时不容易屏蔽，能通过各种 HTTP 代理服务器</li>
</ul>
<h1 id="2-websocket实战"><a href="#2-websocket实战" class="headerlink" title="2. websocket实战"></a>2. websocket实战</h1><h2 id="2-1-server-js"><a href="#2-1-server-js" class="headerlink" title="2.1 server.js"></a>2.1 server.js</h2><p>server.js</p>
<figure class="highlight javascript"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-sju3y4lacl5vpd"></i><span>javascript</span><div class="collapse show" id="collapse-sju3y4lacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> &#123; <span class="hljs-title class_">Server</span> &#125; = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;ws&#x27;</span>);<br><span class="hljs-keyword">const</span> wss = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Server</span>(&#123; <span class="hljs-attr">port</span>: <span class="hljs-number">8888</span> &#125;);<br><span class="hljs-comment">// socket套接字，</span><br>wss.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;connection&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =&gt;</span> &#123;<br>    <span class="hljs-comment">// 通过message来监听客户端发送的消息</span><br>    socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">&#x27;message&#x27;</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> &#123;<br>        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;message: &#x27;</span>,message.<span class="hljs-title function_">toString</span>());<br>        socket.<span class="hljs-title function_">send</span>(message); <span class="hljs-comment">//把消息发送给客户端</span><br>    &#125;);<br>&#125;);<br></code></pre></td></tr></table></div></figure>
<h2 id="2-2-client-js"><a href="#2-2-client-js" class="headerlink" title="2.2 client.js"></a>2.2 client.js</h2><figure class="highlight xml"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-m3u07wlacl5vpd"></i><span>xml</span><div class="collapse show" id="collapse-m3u07wlacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-keyword">html</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">&quot;en&quot;</span>&gt;</span><br><br><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">&quot;UTF-8&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;viewport&quot;</span> <span class="hljs-attr">content</span>=<span class="hljs-string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>websocket<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text&quot;</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;text&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">&quot;send()&quot;</span>&gt;</span>发送<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text/javascript&quot;</span>&gt;</span><span class="language-javascript"></span><br><span class="language-javascript">        <span class="hljs-keyword">let</span> text = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;text&#x27;</span>);</span><br><span class="language-javascript">        <span class="hljs-keyword">var</span> ws = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WebSocket</span>(<span class="hljs-string">&quot;ws://localhost:8888&quot;</span>); <span class="hljs-comment">//在客户端连接服务器</span></span><br><span class="language-javascript">        <span class="hljs-comment">// 当连接打开或者说建立连接后，会触发回调</span></span><br><span class="language-javascript">        ws.<span class="hljs-property">onopen</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;</span><br><span class="language-javascript">            ws.<span class="hljs-title function_">send</span>(<span class="hljs-string">&quot;server&quot;</span>);</span><br><span class="language-javascript">        &#125;;</span><br><span class="language-javascript">        <span class="hljs-comment">// 监听服务器发送给客户端</span></span><br><span class="language-javascript">        ws.<span class="hljs-property">onmessage</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) &#123;</span><br><span class="language-javascript">            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;onmessage&#x27;</span>, event.<span class="hljs-property">data</span>);</span><br><span class="language-javascript">        &#125;;</span><br><span class="language-javascript">        <span class="hljs-keyword">function</span> <span class="hljs-title function_">send</span>(<span class="hljs-params"></span>) &#123;</span><br><span class="language-javascript">            ws.<span class="hljs-title function_">send</span>(text.<span class="hljs-property">value</span>);</span><br><span class="language-javascript">            text.<span class="hljs-property">value</span> = <span class="hljs-string">&#x27;&#x27;</span>;</span><br><span class="language-javascript">        &#125;</span><br><span class="language-javascript">    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span><br></code></pre></td></tr></table></div></figure>

<h1 id="3-websocket连接"><a href="#3-websocket连接" class="headerlink" title="3. websocket连接"></a>3. websocket连接</h1><ul>
<li>WebSocket复用了HTTP的握手通道</li>
<li>具体指的是,客户端通过HTTP请求与WebSocket服务端协商升级协议</li>
<li>协议升级完成后,后续的数据交换则遵照WebSocket的协议<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-00-12.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload><br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-00-36.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload><br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-00-51.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload><h2 id="3-1-客户端：申请协议升级"><a href="#3-1-客户端：申请协议升级" class="headerlink" title="3.1 客户端：申请协议升级"></a>3.1 客户端：申请协议升级</h2></li>
<li>首先客户端发起协议升级请求</li>
<li>请求采用的是标准的HTTP报文格式，且只支持GET方法<figure class="highlight http"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-v00s10lacl5vpd"></i><span>http</span><div class="collapse show" id="collapse-v00s10lacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs http"><span class="hljs-keyword">GET</span> <span class="hljs-string">ws://localhost:8888/</span> <span class="hljs-meta">HTTP/1.1</span><br><span class="hljs-attribute">Host</span><span class="hljs-punctuation">: </span>localhost:8888<br><span class="hljs-attribute">Connection</span><span class="hljs-punctuation">: </span>Upgrade<br><span class="hljs-attribute">Upgrade</span><span class="hljs-punctuation">: </span>websocket<br><span class="hljs-attribute">Sec-WebSocket-Version</span><span class="hljs-punctuation">: </span>13<br><span class="hljs-attribute">Sec-WebSocket-Key</span><span class="hljs-punctuation">: </span>IHfMdf8a0aQXbwQO1pkGdA==<br></code></pre></td></tr></table></div></figure>
字段|    含义</li>
<li>—-|—–<br>Connection: Upgrade|    表示要升级协议<br>Upgrade: websocket|    表示要升级到websocket协议<br>Sec-WebSocket-Version: 13|    表示websocket的版本<br>Sec-WebSocket-Key|    与后面服务端响应首部的Sec-WebSocket-Accept是配套的，提供基本的防护，比如恶意的连接，或者无意义的连接<h2 id="3-2-服务端：响应协议升级"><a href="#3-2-服务端：响应协议升级" class="headerlink" title="3.2 服务端：响应协议升级"></a>3.2 服务端：响应协议升级</h2></li>
<li>服务端返回内容如下<ul>
<li>状态代码101表示协议切换</li>
</ul>
</li>
<li>到此完成协议升级，后续的数据交互都按照新的协议来</li>
</ul>
<figure class="highlight http"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-0g9jfdlacl5vpd"></i><span>http</span><div class="collapse show" id="collapse-0g9jfdlacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs http"><span class="hljs-meta">HTTP/1.1</span> <span class="hljs-number">101</span> Switching Protocols<br><span class="hljs-attribute">Upgrade</span><span class="hljs-punctuation">: </span>websocket<br><span class="hljs-attribute">Connection</span><span class="hljs-punctuation">: </span>Upgrade<br><span class="hljs-attribute">Sec-WebSocket-Accept</span><span class="hljs-punctuation">: </span>aWAY+V/uyz5ILZEoWuWdxjnlb7E=<br></code></pre></td></tr></table></div></figure>
<table>
<thead>
<tr>
<th>字段</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>Connection: Upgrade</td>
<td>升级协议</td>
</tr>
<tr>
<td>Upgrade: websocket</td>
<td>升级到websocket协议</td>
</tr>
<tr>
<td>Sec-WebSocket-Accept</td>
<td>Accept字符串</td>
</tr>
</tbody></table>
<h2 id="3-3-Sec-WebSocket-Accept的计算"><a href="#3-3-Sec-WebSocket-Accept的计算" class="headerlink" title="3.3 Sec-WebSocket-Accept的计算"></a>3.3 Sec-WebSocket-Accept的计算</h2><ul>
<li>Sec-WebSocket-Accept根据客户端请求首部的Sec-WebSocket-Key计算出来</li>
<li>计算公式为：<ul>
<li>将Sec-WebSocket-Key跟258EAFA5-E914-47DA-95CA-C5AB0DC85B11拼接</li>
<li>通过SHA1计算出摘要，并转成base64字符串</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-ecyhzwlacl5vpd"></i><span>javascript</span><div class="collapse show" id="collapse-ecyhzwlacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;crypto&#x27;</span>);<br><span class="hljs-keyword">const</span> <span class="hljs-variable constant_">CODE</span> = <span class="hljs-string">&#x27;258EAFA5-E914-47DA-95CA-C5AB0DC85B11&#x27;</span>;<br><span class="hljs-keyword">function</span> <span class="hljs-title function_">toAcceptKey</span>(<span class="hljs-params">wsKey</span>) &#123;<br>    <span class="hljs-keyword">return</span> crypto.<span class="hljs-title function_">createHash</span>(<span class="hljs-string">&#x27;sha1&#x27;</span>).<span class="hljs-title function_">update</span>(wsKey + <span class="hljs-variable constant_">CODE</span>).<span class="hljs-title function_">digest</span>(<span class="hljs-string">&#x27;base64&#x27;</span>);;<br>&#125;<br><span class="hljs-keyword">const</span> webSocketKey = <span class="hljs-string">&#x27;IHfMdf8a0aQXbwQO1pkGdA==&#x27;</span>;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">toAcceptKey</span>(webSocketKey));<span class="hljs-comment">//aWAY+V/uyz5ILZEoWuWdxjnlb7E=</span><br></code></pre></td></tr></table></div></figure>
<h1 id="4-数据帧格式"><a href="#4-数据帧格式" class="headerlink" title="4. 数据帧格式"></a>4. 数据帧格式</h1><ul>
<li>WebSocket客户端、服务端通信的最小单位是帧，由1个或多个帧组成一条完整的消息（message）</li>
<li>发送端 将消息切割成多个帧，并发送给服务端</li>
<li>接收端 接收消息帧，并将关联的帧重新组装成完整的消息<h2 id="4-1-bit和byte"><a href="#4-1-bit和byte" class="headerlink" title="4.1 bit和byte"></a>4.1 bit和byte</h2></li>
<li>比特就是bit 二进制数系统中,每个0或1就是一个位(bit),位是数据存储的最小单位</li>
<li>其中8个bit就称为一个字节(Byte)<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-03-43.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload></li>
</ul>
<h2 id="4-2-位运算符"><a href="#4-2-位运算符" class="headerlink" title="4.2 位运算符"></a>4.2 位运算符</h2><h3 id="4-2-1-按位与-amp"><a href="#4-2-1-按位与-amp" class="headerlink" title="4.2.1 按位与(&amp;)"></a>4.2.1 按位与(&amp;)</h3><ul>
<li>两个输入数的同一位都为1才为1<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-04-31.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload></li>
</ul>
<h3 id="4-2-2-按位或"><a href="#4-2-2-按位或" class="headerlink" title="4.2.2 按位或(|)"></a>4.2.2 按位或(|)</h3><ul>
<li>两个输入数的同一位只要有一个为1就是1<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-04-47.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload></li>
</ul>
<h3 id="4-2-3-按位异或"><a href="#4-2-3-按位异或" class="headerlink" title="4.2.3 按位异或(^)"></a>4.2.3 按位异或(^)</h3><ul>
<li>两个输入数的同一位不同就是1,如果相同就设为0<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-04-55.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload></li>
</ul>
<h2 id="4-3-数据帧格式"><a href="#4-3-数据帧格式" class="headerlink" title="4.3 数据帧格式"></a>4.3 数据帧格式</h2><ul>
<li>单位是比特 比如FIN、RSV1各占据1比特,opcode占据4比特<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-05-32.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload><figure class="highlight gherkin"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-wdbpw3lacl5vpd"></i><span>gherkin</span><div class="collapse show" id="collapse-wdbpw3lacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs gherkin"> 0                   1                   2                   3<br> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1<br>+-+-+-+-+-------+-+-------------+-------------------------------+<br>|<span class="hljs-string">F</span>|<span class="hljs-string">R</span>|<span class="hljs-string">R</span>|<span class="hljs-string">R</span>|<span class="hljs-string"> opcode</span>|<span class="hljs-string">M</span>|<span class="hljs-string"> Payload len </span>|<span class="hljs-string">    Extended payload length    </span>|<br>|<span class="hljs-string">I</span>|<span class="hljs-string">S</span>|<span class="hljs-string">S</span>|<span class="hljs-string">S</span>|<span class="hljs-string">  (4)  </span>|<span class="hljs-string">A</span>|<span class="hljs-string">     (7)     </span>|<span class="hljs-string">             (16/64)           </span>|<br>|<span class="hljs-string">N</span>|<span class="hljs-string">V</span>|<span class="hljs-string">V</span>|<span class="hljs-string">V</span>|<span class="hljs-string">       </span>|<span class="hljs-string">S</span>|<span class="hljs-string">             </span>|<span class="hljs-string">   (if payload len==126/127)   </span>|<br>|<span class="hljs-string"> </span>|<span class="hljs-string">1</span>|<span class="hljs-string">2</span>|<span class="hljs-string">3</span>|<span class="hljs-string">       </span>|<span class="hljs-string">K</span>|<span class="hljs-string">             </span>|<span class="hljs-string">                               </span>|<br>+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +<br>|<span class="hljs-string">     Extended payload length continued, if payload len == 127  </span>|<br>+ - - - - - - - - - - - - - - - +-------------------------------+<br>|<span class="hljs-string">                               </span>|<span class="hljs-string">Masking-key, if MASK set to 1  </span>|<br>+-------------------------------+-------------------------------+<br>|<span class="hljs-string"> Masking-key (continued)       </span>|<span class="hljs-string">          Payload Data         </span>|<br>+-------------------------------- - - - - - - - - - - - - - - - +<br>:                     Payload Data continued ...                :<br>+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +<br>|<span class="hljs-string">                     Payload Data continued ...                </span>|<br>+---------------------------------------------------------------+<br></code></pre></td></tr></table></div></figure></li>
</ul>
<table>
<thead>
<tr>
<th>字段</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>FIN</td>
<td>1个比特 如果是1,表示这是消息（message）的最后一个分片（fragment）,如果是0,表示不是是消息(message)的最后一个分片(fragment)</td>
</tr>
<tr>
<td>RSV1, RSV2, RSV3</td>
<td>各占1个比特。一般情况下全为0</td>
</tr>
<tr>
<td>Opcode</td>
<td>4个比特,操作代码</td>
</tr>
<tr>
<td>Mask</td>
<td>1个比特。表示是否要对数据载荷进行掩码操作,从客户端向服务端发送数据时，需要对数据进行掩码操作；从服务端向客户端发送数据时，不需要对数据进行掩码操作,如果Mask是1，那么在Masking-key中会定义一个掩码键(masking key),并用这个掩码键来对数据载荷进行反掩码。所有客户端发送到服务端的数据帧，Mask都是1</td>
</tr>
<tr>
<td>Payload length</td>
<td>数据载荷的长度</td>
</tr>
<tr>
<td>Masking-key</td>
<td>0或4字节(32位) 所有从客户端传送到服务端的数据帧,数据载荷都进行了掩码操作,Mask为1,且携带了4字节的Masking-key。如果Mask为0,则没有Masking-key。载荷数据的长度，不包括mask key的长度</td>
</tr>
<tr>
<td>Payload data</td>
<td>载荷数据</td>
</tr>
</tbody></table>
<ul>
<li>Opcode</li>
</ul>
<table>
<thead>
<tr>
<th>字段</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>%x0</td>
<td>表示一个延续帧。当Opcode为0时，表示本次数据传输采用了数据分片，当前收到的数据帧为其中一个数据分片</td>
</tr>
<tr>
<td>%x1</td>
<td>表示这是一个文本帧</td>
</tr>
<tr>
<td>%x2</td>
<td>表示这是一个二进制帧</td>
</tr>
<tr>
<td>%x3-7</td>
<td>保留的操作代码</td>
</tr>
<tr>
<td>%x8</td>
<td>表示连接断开</td>
</tr>
<tr>
<td>%x9</td>
<td>表示这是一个ping操作</td>
</tr>
<tr>
<td>%xA</td>
<td>表示这是一个pong操作</td>
</tr>
<tr>
<td>%xB-F</td>
<td>保留的操作代码</td>
</tr>
</tbody></table>
<h2 id="4-4-Payload-length"><a href="#4-4-Payload-length" class="headerlink" title="4.4 Payload length"></a>4.4 Payload length</h2><ul>
<li>Payload length：数据载荷的长度，单位是字节。为7位，或7+16位，或7+64位<ul>
<li>Payload length=x为0~125：数据的长度为x字节。</li>
<li>Payload length=x为126：后续2个字节代表一个16位的无符号整数，该无符号整数的值为数据的长度</li>
<li>Payload length=x为127：后续8个字节代表一个64位的无符号整数（最高位为0），该无符号整数的值为数据的长度。</li>
<li>如果payload length占用了多个字节的话，payload length的二进制表达采用网络序（big endian，重要的位在前)</li>
</ul>
</li>
<li>readBigUInt64BE 用指定的字节序[readBigInt64BE() 读取为大端序,readBigInt64LE() 读取为小端序]从 buf 中指定的 offset 读取一个有符号的 64 位整数值</li>
<li>Big-endian(大端序) 高位字节在前</li>
<li>Little-endian(小端序) 低位字节在前<figure class="highlight maxima"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-baeu86lacl5vpd"></i><span>maxima</span><div class="collapse show" id="collapse-baeu86lacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs maxima"><span class="hljs-built_in">let</span> buffer = Buffer.from([<span class="hljs-number">0b00000001</span>, <span class="hljs-number">0b00000000</span>]);<br>console.<span class="hljs-built_in">log</span>(Math.pow(<span class="hljs-number">2</span>, <span class="hljs-number">8</span>));<br>console.<span class="hljs-built_in">log</span>(buffer.readUInt16BE(<span class="hljs-number">0</span>));// <span class="hljs-number">00000001</span> <span class="hljs-number">00000000</span><br>console.<span class="hljs-built_in">log</span>(buffer.readUInt16LE(<span class="hljs-number">0</span>));// <span class="hljs-number">00000000</span> <span class="hljs-number">00000001</span><br></code></pre></td></tr></table></div></figure>
<figure class="highlight maxima"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-0zpqy0lacl5vpd"></i><span>maxima</span><div class="collapse show" id="collapse-0zpqy0lacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs maxima">function getLength(buffer) &#123;<br>    const byte = buffer.readUInt8(<span class="hljs-number">1</span>);<br>    <span class="hljs-built_in">let</span> <span class="hljs-built_in">length</span> = parseInt(byte.toString(<span class="hljs-number">2</span>).<span class="hljs-built_in">substring</span>(<span class="hljs-number">1</span>), <span class="hljs-number">2</span>);<br>    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">length</span> === <span class="hljs-number">126</span>) &#123;<br>        <span class="hljs-built_in">length</span> = buffer.readUInt16BE(<span class="hljs-number">2</span>);<br>    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-built_in">length</span> === <span class="hljs-number">127</span>) &#123;<br>        <span class="hljs-built_in">length</span> = buffer.readBigUInt64BE(<span class="hljs-number">2</span>);<br>    &#125;<br>    <span class="hljs-built_in">return</span> <span class="hljs-built_in">length</span>;<br>&#125;<br>console.<span class="hljs-built_in">log</span>(<span class="hljs-number">126</span>..toString(<span class="hljs-number">2</span>));<br>console.<span class="hljs-built_in">log</span>(<span class="hljs-number">127</span>..toString(<span class="hljs-number">2</span>));<br>console.<span class="hljs-built_in">log</span>(getLength(Buffer.from([<span class="hljs-number">0b10000001</span>, <span class="hljs-number">0b10000001</span>])));<br>console.<span class="hljs-built_in">log</span>(getLength(Buffer.from([<span class="hljs-number">0b10000001</span>, <span class="hljs-number">0b11111110</span>, <span class="hljs-number">0b00000000</span>, <span class="hljs-number">0b00000001</span>])));<br>console.<span class="hljs-built_in">log</span>(getLength(Buffer.from([<span class="hljs-number">0b10000001</span>, <span class="hljs-number">0b11111111</span>, <span class="hljs-number">0b00000000</span>, <span class="hljs-number">0b00000000</span>, <span class="hljs-number">0b00000000</span>, <span class="hljs-number">0b00000000</span>, <span class="hljs-number">0b00000000</span>, <span class="hljs-number">0b00000000</span>, <span class="hljs-number">0b00000000</span>, <span class="hljs-number">0b00000001</span>])));<br></code></pre></td></tr></table></div></figure>
<h2 id="4-5-掩码算法"><a href="#4-5-掩码算法" class="headerlink" title="4.5 掩码算法"></a>4.5 掩码算法</h2></li>
<li>掩码键（Masking-key）是由客户端挑选出来的32bit的随机数,掩码操作不会影响数据载荷的长度</li>
<li>掩码和反掩码操作都采用如下算法</li>
<li>对索引i模以4得到结果并对原来的索引进行异或操作<br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-08-09.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload><br><img src="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/network/websocket/ikki-2022-04-27-21-08-18.png" srcset="https://ikkiss.oss-cn-hangzhou.aliyuncs.com/images/myblog/loading.gif" lazyload><figure class="highlight arcade"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-743n12lacl5vpd"></i><span>arcade</span><div class="collapse show" id="collapse-743n12lacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs arcade"><span class="hljs-keyword">function</span> <span class="hljs-title function_">unmask</span>(<span class="hljs-params">buffer, mask</span>) &#123;<br>    const <span class="hljs-built_in">length</span> = <span class="hljs-built_in">buffer</span>.<span class="hljs-built_in">length</span>;<br>    <span class="hljs-keyword">for</span> (let i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">length</span>; i++) &#123;<br>        <span class="hljs-built_in">buffer</span>[i] ^= mask[i % <span class="hljs-number">4</span>];<br>    &#125;<br>&#125;<br><br>let mask = <span class="hljs-built_in">Buffer</span>.from([<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>]);<br>let <span class="hljs-built_in">buffer</span> = <span class="hljs-built_in">Buffer</span>.from([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>]);<br>unmask(<span class="hljs-built_in">buffer</span>, mask);<br><span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-built_in">buffer</span>);<br></code></pre></td></tr></table></div></figure>
<h1 id="5-实现websocket服务器"><a href="#5-实现websocket服务器" class="headerlink" title="5. 实现websocket服务器"></a>5. 实现websocket服务器</h1><figure class="highlight maxima"><i class="iconfont icon-top" type="button" data-toggle="collapse" data-target="#collapse-yjzewzlacl5vpd"></i><span>maxima</span><div class="collapse show" id="collapse-yjzewzlacl5vpd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br></pre></td><td class="code"><pre><code class="hljs maxima">const net = require(&#x27;net&#x27;);<br>const &#123; EventEmitter &#125; = require(&#x27;events&#x27;);<br>const crypto = require(&#x27;crypto&#x27;);<br>const CODE = &#x27;258EAFA5-E914-47DA-95CA-C5AB0DC85B11&#x27;;<br>const OP_CODES = &#123;<br>    TEXT: <span class="hljs-number">1</span>,<br>    BINARY: <span class="hljs-number">2</span><br>&#125;;<br>class Server extends EventEmitter &#123;<br>    constructor(options) &#123;<br>        super(options);<br>        this.options = options;<br>        this.server = net.createServer(this.listener);<br>        this.server.listen(options.port);<br>    &#125;<br>    listener = (socket) =&gt; &#123;<br>        socket.setKeepAlive(<span class="hljs-literal">true</span>);<br>        socket.send = function (payload) &#123;<br>            <span class="hljs-built_in">let</span> _opcode;<br>            <span class="hljs-keyword">if</span> (Buffer.isBuffer(payload)) &#123;<br>                _opcode = OP_CODES.BINARY;<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                _opcode = OP_CODES.TEXT;<br>                payload = Buffer.from(payload);<br>            &#125;<br>            <span class="hljs-built_in">let</span> <span class="hljs-built_in">length</span> = payload.<span class="hljs-built_in">length</span>;<br>            <span class="hljs-built_in">let</span> buffer = Buffer.alloc(<span class="hljs-number">2</span> + <span class="hljs-built_in">length</span>);<br>            buffer[<span class="hljs-number">0</span>] = <span class="hljs-number">0b10000000</span> | _opcode;<br>            buffer[<span class="hljs-number">1</span>] = <span class="hljs-built_in">length</span>;<br>            payload.<span class="hljs-built_in">copy</span>(buffer, <span class="hljs-number">2</span>);<br>            socket.write(buffer);<br>        &#125;<br>        socket.on(&#x27;data&#x27;, (chunk) =&gt; &#123;<br>            <span class="hljs-keyword">if</span> (chunk.toString().match(/Upgrade: websocket/)) &#123;<br>                this.upgrade(socket, chunk.toString());<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                this.onmessage(socket, chunk);<br>            &#125;<br>        &#125;);<br>        this.emit(&#x27;connection&#x27;, socket);<br>    &#125;<br>    onmessage = (socket, chunk) =&gt; &#123;<br>        <span class="hljs-built_in">let</span> FIN = (chunk[<span class="hljs-number">0</span>] &amp; <span class="hljs-number">0b10000000</span>) === <span class="hljs-number">0b10000000</span>;//判断是否是结束位,第一个bit是不是<span class="hljs-number">1</span><br>        <span class="hljs-built_in">let</span> opcode = chunk[<span class="hljs-number">0</span>] &amp; <span class="hljs-number">0b00001111</span>;//取一个字节的后四位,得到的一个是十进制数<br>        <span class="hljs-built_in">let</span> masked = (chunk[<span class="hljs-number">1</span>] &amp; <span class="hljs-number">0b10000000</span>) === <span class="hljs-number">0b10000000</span>;//第一位是否是<span class="hljs-number">1</span><br>        <span class="hljs-built_in">let</span> payloadLength = chunk[<span class="hljs-number">1</span>] &amp; <span class="hljs-number">0b01111111</span>;//取得负载数据的长度<br>        <span class="hljs-built_in">let</span> payload;<br>        <span class="hljs-keyword">if</span> (masked) &#123;<br>            <span class="hljs-built_in">let</span> masteringKey = chunk.slice(<span class="hljs-number">2</span>, <span class="hljs-number">6</span>);//掩码<br>            payload = chunk.slice(<span class="hljs-number">6</span>);//负载数据<br>            unmask(payload, masteringKey);//对数据进行解码处理<br>        &#125;<br>        <span class="hljs-keyword">if</span> (FIN) &#123;<br>            switch (opcode) &#123;<br>                case OP_CODES.TEXT:<br>                    socket.emit(&#x27;message&#x27;, payload.toString());<br>                    <span class="hljs-built_in">break</span>;<br>                case OP_CODES.BINARY:<br>                    socket.emit(&#x27;message&#x27;, payload);<br>                    <span class="hljs-built_in">break</span>;<br>                default:<br>                    <span class="hljs-built_in">break</span>;<br>            &#125;<br>        &#125;<br>    &#125;<br>    upgrade = (socket, chunk) =&gt; &#123;<br>        <span class="hljs-built_in">let</span> rows = chunk.<span class="hljs-built_in">split</span>(&#x27;\r\n&#x27;);//按分割符分开<br>        <span class="hljs-built_in">let</span> headers = toHeaders(rows.slice(<span class="hljs-number">1</span>, -<span class="hljs-number">2</span>));//去掉请求行和尾部的二个分隔符<br>        <span class="hljs-built_in">let</span> wsKey = headers[&#x27;Sec-WebSocket-Key&#x27;];<br>        <span class="hljs-built_in">let</span> acceptKey = toAcceptKey(wsKey);<br>        <span class="hljs-built_in">let</span> response = [<br>            &#x27;HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">101</span> Switching Protocols&#x27;,<br>            &#x27;Upgrade: websocket&#x27;,<br>            `Sec-WebSocket-Accept: $&#123;acceptKey&#125;`,<br>            &#x27;Connection: Upgrade&#x27;,<br>            &#x27;\r\n&#x27;<br>        ].<span class="hljs-built_in">join</span>(&#x27;\r\n&#x27;);<br>        socket.write(response);<br>    &#125;<br>&#125;<br>function toAcceptKey(wsKey) &#123;<br>    <span class="hljs-built_in">return</span> crypto.createHash(&#x27;sha1&#x27;).update(wsKey + CODE).digest(&#x27;<span class="hljs-built_in">base64</span>&#x27;);;<br>&#125;<br>function toHeaders(rows) &#123;<br>    const headers = &#123;&#125;;<br>    rows.forEach(<span class="hljs-built_in">row</span> =&gt; &#123;<br>        <span class="hljs-built_in">let</span> [<span class="hljs-built_in">key</span>, value] = <span class="hljs-built_in">row</span>.<span class="hljs-built_in">split</span>(&#x27;: &#x27;);<br>        headers[<span class="hljs-built_in">key</span>] = value;<br>    &#125;);<br>    <span class="hljs-built_in">return</span> headers;<br>&#125;<br>function unmask(buffer, mask) &#123;<br>    const <span class="hljs-built_in">length</span> = buffer.<span class="hljs-built_in">length</span>;<br>    <span class="hljs-keyword">for</span> (<span class="hljs-built_in">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">length</span>; i++) &#123;<br>        buffer[i] ^= mask[i &amp; <span class="hljs-number">3</span>];<br>    &#125;<br>&#125;<br><br>exports.Server = Server;<br></code></pre></td></tr></table></div></figure></li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E7%BD%91%E7%BB%9C%E7%9F%A5%E8%AF%86/" class="category-chain-item">网络知识</a>
  
  
    <span>></span>
    
  <a href="/categories/%E7%BD%91%E7%BB%9C%E7%9F%A5%E8%AF%86/websocket/" class="category-chain-item">websocket</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E7%BD%91%E7%BB%9C%E7%9F%A5%E8%AF%86/">#网络知识</a>
      
        <a href="/tags/websocket/">#websocket</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>websocket</div>
      <div>http://81.68.132.127/2022/09/27/network/websocket/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Ikki</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年9月27日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2022年10月7日</div>
        </div>
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/09/30/node/%E4%B8%80%E6%96%87%E6%90%9E%E5%AE%9A%E5%89%8D%E5%90%8E%E7%AB%AF%E9%89%B4%E6%9D%83/" title="最全前后端鉴权方案">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">最全前后端鉴权方案</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/09/23/network/ISO%E4%B8%83%E5%B1%82%E6%A8%A1%E5%9E%8B/" title="ISO七层模型">
                        <span class="hidden-mobile">ISO七层模型</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  <article id="comments" lazyload>
    
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"6KzYWc2oaEBaHgNl4UIicMJC-gzGzoHsz","appKey":"vJ4FIwKeHRmHraCJraAsjyZ7","path":"window.location.pathname","placeholder":"请输入你的评论\n昵称为必填项目(输入QQ号码可以自动获取昵称和邮箱)\n虽然email不是必选，但是填写了email可以收到推送通知哦！","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":true,"recordIP":true,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":true},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


  </article>


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
      IKKI-专业BUG开发
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="/fluid/js/star.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
